const db = require("../common/db/index")
const Jwt = require("../common/jwt")

module.exports = {
    // 用户注册（检查账号是否已存在）
    register(account, password, username, createAt, gender = "", imgUrl = "", role = '0') {
        return new Promise(async (resolve, reject) => {
            const sql = 'SELECT account FROM pre_user WHERE account = ?';
            const rows = await db.query(sql, [account]);
            if (rows.length == 0) {
                const sql = 'INSERT INTO pre_user (account, password, username,createAt, gender, imgUrl, role) VALUES (?, ?, ?,?,?, ?,?)';
                db.query(sql, [account, password, username, createAt, gender, imgUrl, role])
                    .then(
                        result => {
                            resolve({
                                result,
                                msg: "恭喜你,注册成功",
                                code: 200
                            })
                        },
                        err => {
                            reject(err)
                        }
                    )
            }
            else {
                resolve({
                    msg: "该账号已存在",
                    code: 1
                })
            }
        })
    },

    // 用户登录（验证账号密码，生成token）
    login(account, password) {
        return new Promise(async (resolve, reject) => {
            const sql = 'SELECT account,username,gender,imgUrl,createAt, password, id, role FROM pre_user WHERE account = ?';
            db.query(sql, [account])
                .then(
                    result => {
                        if (result.length == 0) {
                            resolve({
                                msg: "不存在该用户"
                            })
                        }
                        else {
                            if (result[0].role == '-2') {
                                resolve({
                                    msg: "该账号已被封禁，请更换账号登录或联系管理员解封",
                                    code: -2
                                })
                                return
                            }

                            let isLogin = password === result[0].password
                            if (isLogin) {
                                let user = result[0];
                                let token = new Jwt(user.id).getToken();
                                resolve({
                                    username: user.username,
                                    account: user.account,
                                    gender: user.gender,
                                    createAt: user.createAt,
                                    imgUrl: user.imgUrl,
                                    role: user.role,
                                    token: token,
                                    msg: "登录成功",
                                    code: 200
                                })
                            }
                            else {
                                resolve({
                                    msg: "登录失败",
                                    code: -1
                                })
                            }
                        }

                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },

    // 删除用户
    remove(id) {
        return new Promise((resolve, reject) => {
            const sql = 'DELETE FROM pre_user WHERE id = ?';
            db.query(sql, [id])
                .then(
                    result => {
                        resolve({
                            msg: "删除成功",
                            result
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },

    // 获取用户列表（分页，包含管理员数量统计）
    items(page_num, page_size) {
        return new Promise(async (resolve, reject) => {
            const rows = await db.query(`SELECT count(*) as total FROM pre_user`);
            const adminRows = await db.query(`SELECT count(*) as adminCount FROM pre_user WHERE role = '1'`);
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = `select * from pre_user limit ${page_num2} , ${page_size2}`
            await db.query(sql)
                .then(
                    data => {
                        resolve({
                            code: 200,
                            total: rows[0].total,
                            adminCount: adminRows[0].adminCount || 0,
                            data,
                            msg: "获取用户列表"
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },

    // 修改用户信息
    modify(username, gender, imgUrl, id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_user SET username = ?, gender = ? , imgUrl = ? WHERE id = ?';
            db.query(sql, [username, gender, imgUrl, id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "修改用户信息成功"
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },

    // 搜索用户（按账号或用户名模糊查询）
    search(keyword) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT account,username,gender,imgUrl,createAt FROM pre_user WHERE account LIKE ? or username LIKE ? ';
            db.query(sql, [`%${keyword}%`, `%${keyword}%`])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "搜索用户成功"
                        })
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
    // 获取用户详情
    detail(id) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, username, account, gender, imgUrl, createAt FROM pre_user WHERE id = ?';
            db.query(sql, [Number(id)])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 禁言用户（设置角色为-1）
    mute(id, muteTime) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_user SET role = ? WHERE id = ?';
            db.query(sql, ['-1', id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "禁言成功",
                            code: 200
                        })
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
    // 封禁用户（设置角色为-2）
    ban(id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_user SET role = ? WHERE id = ?';
            db.query(sql, ['-2', id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "封禁成功",
                            code: 200
                        })
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
    // 解禁用户（恢复角色为0）
    unmute(id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_user SET role = ? WHERE id = ?';
            db.query(sql, ['0', id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "解禁成功",
                            code: 200
                        })
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
    // 解封用户（恢复角色为0）
    unban(id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_user SET role = ? WHERE id = ?';
            db.query(sql, ['0', id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "解封成功",
                            code: 200
                        })
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
}